<?php

namespace app\admin\controller\exam;

use addons\exam\model\QuestionModel;
use app\common\controller\Backend;
use think\db;

/**
 * 试卷
 *
 * @icon fa fa-circle-o
 */
class PapersMain extends Backend
{
    protected $noNeedRight = ['*'];
    /**
     * Papers模型对象
     * @var \app\admin\model\exam\Papers
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\exam\Papers;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($where)
                    ->where(['is_main'=>2])
                    ->order($sort, $order)
                    ->paginate($limit);
            $rows = $list->toArray()['data'];
            foreach ($rows as &$row)
            {
//                $row->visible(['id','title','describe','createtime','accuracy','profile_id']);
                if($row['profile_id'] == 0)
                {
                    $db2 = Db::connect('db2');
                    $alist = $db2->name('admin')->find($row['uid']);
                    $row['realname'] = $alist['nickname'];
                }
                else
                {
                    $db2 = Db::connect('db2');
                    $row['realname'] = $db2->name('classes_teacher')->where('profile_id',$row['profile_id'])->value('realname');
                }
            }

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    //获取单个题
    public function getOne()
    {
        if ($this->request->isAjax())
        {
            $id = $this->request->request('id');
            $list = Db::name('exam_question')->find($id);
            $cwhere = [ 'id' => $list['cate_id'] ];
            $clist = Db::name('exam_cate')->field('name')->where($cwhere)->find();

            $list['name'] = $clist['name'] . ' - ' . $list['id'];

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => $list,
            ];
            return json($result);
        }
    }

     /**
     * 获取单个试题
     * auth:zlq
     * data:2023.09.08
     */
    public function get_view()
    {
        if ($this->request->isAjax())
        {
            $qid = $this->request->request('qid');
                
            $row = QuestionModel::get($qid);

            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                if (!in_array($row[$this->dataLimitField], $adminIds)) {
                    $this->error(__('You have no permission'));
                }
            }
            $data = array();
            switch ($row['kind']) {
                case 'SINGLE':
                    $data['kind'] = '单选题';
                    break;
                case 'JUDGE':
                    $data['kind'] = '判断题';
                    break;
                case 'MULTI':
                    $data['kind'] = '多选题';
                    break;
                case 'FILL':
                    $data['kind'] = '填空题';
                    break;
                default:
                    $data['kind'] = '单选题';
            }
            switch ($row['difficulty']) {
                case 'EASY':
                    $data['difficulty'] = '简单';
                    break;
                case 'GENERAL':
                    $data['difficulty'] = '普通';
                    break;
                case 'MULTI':
                    $data['HARD'] = '困难';
                    break;
                default:
                    $data['difficulty'] = '单选题';
            }
            $data['describe'] = $row['describe'];
            $data['title'] = $row['title'];
            $data['answer'] = $row['answer'];
            $data['id'] = $row['id'];
            $data['other_url'] = $row['other_url'];
            $data['other_name'] = $row['other_name'];
            if (is_string($row['options_json']))  $data['options_json'] = json_decode($row['options_json'], true);

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => $data,
            ];
            return json($result);
        }
    }
    /**
     * iframe加载
     * auth:zlq
     * data:2023.09.08
     */
    public function get_views($ids = null)
    {
        $row = QuestionModel::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        if (is_string($row['options_json'])) {
            $row['options_json'] = json_decode($row['options_json'],true);
        }
        // dump($row['options_json']);exit;
        $this->view->assign("options_json", $row['options_json']);
        return $this->view->fetch();
    }

    //添加/修改试卷
    public function xgsj()
    {
        if ($this->request->isAjax())
        {
            $question_ids = $this->request->request('question_ids');
            $describe = $this->request->request('describe');
            $title = $this->request->request('title');
            $papers_id = $this->request->request('papers_id');
            $question_ids = trim($question_ids,',');

            Db::startTrans();
            try {

                $data = [
                    'title' => $title,
                    'describe' => $describe,
                    'question_ids' => $question_ids,
                ];

                if ($papers_id>0) {
                    Db::name('exam_papers')->where(['id'=>$papers_id])->update($data);
                } else {
                    $data['createtime'] = time();
                    $data['is_main'] = 2;
                    Db::name('exam_papers')->insert($data);
                }


                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => [],
            ];
            return json($result);
        }
    }

     /**
     * 获取试题列表
     * auth:zlq
     * data:2023.09.08
     */
    public function get_question()
    {
        if ($this->request->isAjax())
        {

            $cid = $this->request->request('cid');
            $where = [
                'cate_id' => $cid,
                'deletetime' => null
            ];
            $list = Db::table('fa_exam_question')->field('id')->where($where)->order('id asc')->select();

            if (!empty($list))
            {
                $number = count($list);
                $cwhere = [ 'id' => $cid ];
                $clist = Db::table('fa_exam_cate')->field('name')->where($cwhere)->find();
                foreach ($list as $k => $v)
                {
                    $num = $k+1;
                    if($num < 10)
                    {
                        $num = '0'.$num;
                    }
//                    $list[$k]['name'] = $clist['name'] . ' - ' . $num;
                    $list[$k]['name'] = $clist['name'] . ' - ' . $v['id'];
                }
                $where1 = [
                    'parent_id' => $cid,
                    'kind' => 'QUESTION',
                    'deletetime' => null
                ];
                $clist1 = Db::table('fa_exam_cate')->where($where1)->order('sort asc')->select();
                if(!empty($clist1))
                {
                    $list1 = $clist1;
                }
                else
                {
                    $list1 = [];
                }

                $result = [
                    'msg' => 'success',
                    'code' => 100,
                    'data' => $list,
                    'num' => $number,
                    'list' => $list1
                ];
            }
            else
            {
                $where1 = [
                    'parent_id' => $cid,
                    'kind' => 'QUESTION',
                    'deletetime' => null
                ];
                $clist1 = Db::table('fa_exam_cate')->where($where1)->order('sort asc')->select();
                if(!empty($clist1))
                {
                    $list1 = $clist1;
                }
                else
                {
                    $list1 = [];
                }
                $result = [
                    'msg' => 'success',
                    'code' => 101,
                    'data' => $list,
                    'num' => 0,
                    'list' => $list1
                ];
            }

            return json($result);
        }
    }

    public function question($ids = null)
    {

        if ($this->request->isAjax()) {
            $id = $this->request->get("id");
            $limit = $this->request->get("limit");
            $offset = $this->request->get("offset");
            $page = $offset / $limit + 1;
//            dump($this->request->get());die;
            $plist = Db::name('exam_papers')->find($id);

            $where['a.id'] = ['in',$plist['question_ids']];
            $db2 = Db::connect('db2');
            $questions_list = $db2->name('exam_question a')
                ->join('fa_exam_cate b','a.cate_id=b.id')
                ->where($where)
                ->field('a.*,b.name as cate_name')
                ->page($page,$limit)
                ->select();
            $total = $db2->name('exam_question a')->where($where)->count();
//            dump($questions_list);die;
            $result = array("total" => $total, "rows" => $questions_list);

            return json($result);
        }
        $this->view->assign('id',$ids);
        return $this->view->fetch();
    }

    public function question1($ids = null)
    {

        if ($this->request->isAjax()) {
            $id = $this->request->get("id");
            $limit = $this->request->get("limit");
            $offset = $this->request->get("offset");
            $page = $offset / $limit + 1;
//            dump($this->request->get());die;
            $plist = Db::name('exam_papers')->find($id);

            $where['a.id'] = ['in',$plist['question_ids']];
            $questions_list = Db::name('exam_question a')
                ->join('fa_exam_cate b','a.cate_id=b.id')
                ->where($where)
                ->field('a.*,b.name as cate_name')
                ->page($page,$limit)
                ->select();
            $total = Db::name('exam_question a')->where($where)->count();
//            dump($questions_list);die;
            $result = array("total" => $total, "rows" => $questions_list);

            return json($result);
        }
        $this->view->assign('id',$ids);
        return $this->view->fetch();
    }

    public function classes($ids = null)
    {

        if ($this->request->isAjax()) {
            $id = $this->request->get("id");
            $search = $this->request->get("search");
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $plist = Db::name('exam_papers')->find($id);
            $arr = [];
            if(!empty($plist['classes_ids']))
            {
                $arr = explode(',',$plist['classes_ids']);
            }

            $nwhere['a.uid'] = get_admin_id($this->auth->id);
            $nwhere['a.disable'] = 0;
            if(!empty($search))
            {
                $nwhere['a.title'] = ['like','%' . $search . '%'];
            }

            $auth = Db::name('auth_group_access')->where('uid',$this->auth->id)->find();
            if($auth['group_id'] == 3)
            {
                $tlist = Db::name('classes_teacher')->where('user_id',$this->auth->id)->find();
                $nwhere['a.profile_id'] = $tlist['profile_id'];
            }
            $list = Db::name('classes_class a')
                ->join('fa_classes_teacher b','a.profile_id=b.profile_id')
                ->where($nwhere)
                ->field('a.*,b.realname,b.mobile')
                ->order('id desc')
                ->paginate($limit);
//            $total = Db::name('classes_class a')->where($where)->count();
            $total = $list->total();
            $rows = $list->items();
            foreach ($rows as $k => $row)
            {
                $rows[$k]['status'] = 0;
                if(in_array($row['id'],$arr))
                {
                    $rows[$k]['status'] = 1;
                }
            }
            $result = array("total" => $total, "rows" => $rows);

            return json($result);
        }
        $this->view->assign('id',$ids);
        return $this->view->fetch();
    }
    public function expandclass($ids = null)
    {
        $paper_id = $this->request->request("paper_id");

        $this->view->assign("paper_id", $paper_id);
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }
    //绑定班级
    public function bd_class()
    {
        if ($this->request->isPost())
        {
            $paper_id = $this->request->post('paper_id');
            $ids = $this->request->post('ids');
            $num = $this->request->post('num');
            $end_time = $this->request->post('end_time');
            $start_time = $this->request->post('start_time');
            $title = $this->request->post('title');

            if(strtotime($start_time) > strtotime($end_time))
            {
                $this->error('发布时间大于结束时间');
            }

            $paper_list = Db::name('exam_papers')->find($paper_id);

            $data_gl = [
                'papers_id' => $paper_id,
                'title' => $title,
                'question_ids' => $paper_list['question_ids'],
                'classes_id' => $ids,
                'createtime' => time(),
                'uid' => $this->auth->id,
                'num' => $num,
                'end_time' => strtotime($end_time),
                'start_time' => strtotime($start_time),
            ];
            $papers_gl_id = Db::name('exam_papers_gl')->insertGetId($data_gl);
            $data = [
                'papers_id' => $paper_id,
                'papers_gl_id' => $papers_gl_id,
                'class_id' => $ids,
                'num' => $num,
                'end_time' => strtotime($end_time),
                'start_time' => strtotime($start_time),
            ];
//            dump($ids);die;
            $student = Db::name('user')->where('classs',$ids)->select();

            if(!empty($student))
            {
                foreach($student as $k => $v)
                {
                    $data['user_id'] = $v['id'];
                    Db::name('exam_user_papers')->insert($data);
                }
            }

            if(empty($paper_list['classes_ids']))
            {
                $classes_ids = $ids;
            }
            else
            {
                $classes_ids = $paper_list['classes_ids'] . ',' . $ids;
            }

            $info = Db::name('exam_papers')->where('id',$paper_id)->update(['classes_ids'=>$classes_ids]);

            if($info)
            {
                $this->success();
            }
            else
            {
                $this->error();
            }
        }
    }
    //解绑班级
    public function jb_class($ids = null)
    {
        if ($this->request->isAjax())
        {
            $paper_id = $this->request->get('paper_id');
            $paper_list = Db::name('exam_papers')->find($paper_id);

            $where_gl = [
                'papers_id' => $paper_id,
                'classes_id' => $ids
            ];

            $classes_ids_arr = explode(',',$paper_list['classes_ids']);
            foreach ($classes_ids_arr as $k =>$v)
            {
                if($ids == $v)
                {
                    unset($classes_ids_arr[$k]);
                }
            }
            $classes_ids = implode(',',$classes_ids_arr);
            if(empty($classes_ids))
            {
                $classes_ids = null;
            }
            Db::name('exam_user_papers')->where(['papers_id'=>$paper_id,'class_id'=>$ids])->delete();
            Db::name('exam_papers_gl')->where($where_gl)->delete();
            $info = Db::name('exam_papers')->where('id',$paper_id)->update(['classes_ids'=>$classes_ids]);

            if($info)
            {
                $this->success();
            }
            else
            {
                $this->error();
            }
        }
    }

    public function papers_share($ids = null)
    {
        $db2 = Db::connect('db2');
        if ($this->request->isPost())
        {
            $papers_id = $this->request->post('papers_id');
            $option = $this->request->post('option');
            $info = Db::name('exam_papers')->find($papers_id);


            // if($option == 1)
            // {
                $profile_id = $this->request->post('profile_id');
                // if($info['profile_id'] == $profile_id)
                // {
                //     $this->error('无法共享给创建者');
                // }
                // $share_ids = $info['share_ids'] . ',' . $profile_id;
                // $db2_info = Db::name('exam_papers')->where('id',$papers_id)->update(['share_ids'=>$share_ids]);

            // }
            // else
            // {
                $where = [
                    'title' => $info['title'],
                    'uid' => $profile_id,
                    'is_main' => 2
                    // 'profile_id' => $info['profile_id'],
                ];
                $db2_info = $db2->name('exam_papers')->where($where)->find();
                if(!empty($db2_info))
                {
                    $this->error('重复分享');
                }
                unset($info['id']);
                unset($info['createtime']);
                $info['createtime'] = time();
                $info['uid'] = $profile_id;
                $info['is_main'] = 2;
                $db2->name('exam_papers')->insert($info);
            // }
            $this->success();
        }
        $list = $db2->name('admin')->select();
        $this->view->assign("list", $list);
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }

    public function view($ids = null)
    {
        $db2 = Db::connect('db2');
        $row = $db2->name('exam_question')->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
       $kindList = [
            "JUDGE" => "判断题",
            "SINGLE" => "单选题",
            "MULTI" => "多选题",
            "FILL" => "填空题",
        ];

        $this->view->assign("kindList", $kindList);
        $this->view->assign("row", $row);
        $options_json = json_decode($row['options_json'],true);
        // dump($options_json);exit;
        $this->view->assign("options_json", $options_json);
        return $this->view->fetch();
    }

      /**
     * 添加/编辑
     */
    public function papers_edit($ids = null)
    {

        $where = [
            'kind' => 'QUESTION',
            'level' => 1,
            'deletetime' => null,
        ];
        $list = Db::name('exam_cate')->where($where)->order('sort asc')->select();
        $papers = [];
        if ($ids) $papers = Db::name('exam_papers')->find($ids);

        $this->view->assign('list', $list);
        $this->view->assign('papers', $papers);

        return $this->view->fetch();
    }

    //papers全部
    public function getAll()
    {
        if ($this->request->isAjax())
        {
            $papers_id = $this->request->request('papers_id');

            $papers = Db::name('exam_papers')->find($papers_id);
            $where['id'] = ['in',$papers['question_ids']];
            $list = Db::name('exam_question')->where($where)->order('id asc')->select();

            if (!empty($list))
            {
                foreach ($list as $k => $v)
                {
                    $cwhere = ['id' => $v['cate_id']];
                    $clist = Db::name('exam_cate')->field('name')->where($cwhere)->find();
                    $list[$k]['name'] = $clist['name'] . ' - ' . $v['id'];
                }
            }
            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => $list,
            ];
            return json($result);
        }
    }
}
